#define _CRT_SECURE_NO_WARNINGS

#include"conemt.h"

Link* createLink(void)
{
	Link* pLink = (Link*)malloc(sizeof(Link));
	if (NULL == pLink)
	{
		perror("pLink error");
		return NULL;
	}
	memset(pLink, 0, sizeof(Link));
	return pLink;
}

int insertLink(Link* pHaed, int pos, data_type item)
{
	if (NULL == pHaed)
	{
		return LINKNULL;
	}
	Link* pHew = createLink();
	pHew->data = item;
	Link* pFind = NULL;
	int i = 0;
	switch (pos)
	{
	case HEAD:
		if (pHaed->pNext != NULL)
		{
			pHew->pNext = pHaed->pNext;
		}
		pHaed->pNext = pHew;
		break;
	case TAIL:
		pFind = pHaed;
		while (pFind->pNext != NULL)
		{
			pFind = pFind->pNext;
		}
		pFind->pNext = pHew; 
		break;
	default:
		pFind = pHaed;
		while (pFind != NULL && i < pos - 1)
		{
			pFind = pFind->pNext;
			i++;
		}
		if (NULL == pFind)
		{
			return POSERROR;
		}
		pHew->pNext = pFind->pNext;
		pFind->pNext = pHew;
	}
	return OK;
}
int showLink(Link* pHaed)
{
	if (NULL == pHaed)
	{
		return LINKNULL;
	}
	Link* pFind = pHaed->pNext;
	while (pFind != NULL)
	{
		printf("%d ", pFind->data);
		pFind = pFind->pNext;
	}
	printf("\n");
	return OK;
}

int deleteLink(Link* pHaed, int pos, data_type* pData)
{
	if (NULL == pHaed)
	{
		return LINKNULL;
	}
	Link* pDel = NULL;
	Link* pFind = NULL;
	int i = 0;
	switch (pos)
	{
	case HEAD:
		pDel = pHaed->pNext;
		if (NULL == pDel)
		{
			return EMPTY;
		}
		*pData = pDel->data;
		pHaed->pNext = pDel->pNext;
		free(pDel);
		pDel = NULL;
		break;
	case TAIL:
		pFind = pHaed;
		pDel = pHaed->pNext;
		if (NULL == pDel)
		{
			return EMPTY;
		}
		while (pDel->pNext != NULL)
		{
			pFind = pFind->pNext;
			pDel = pDel->pNext;
		}
		*pData = pDel->data;
		pFind->pNext = NULL;

		free(pDel);
		pDel = NULL;
		break;
	default:
		pFind = pHaed;
		pDel = pHaed->pNext;
		if (NULL == pDel)
		{
			return EMPTY;
		}
		while (pos-1 > i && pDel != NULL)
		{
			pFind = pDel;
			pDel = pDel->pNext;
			i++;
		}
		if (pDel == NULL)
		{
			return POSERROR;
		}
		*pData = pDel->data;
		pDel->pNext = pFind->pNext;

		free(pDel);
		pDel = NULL;
		break;
	}
}

int destroyLink(Link** pHaed)
{
	if (NULL == *pHaed)
	{
		return LINKNULL;
	}
	while (1)
	{
		Link* pDel = (*pHaed)->pNext;
		if (NULL == pDel)
		{
			break;
		}
		(*pHaed)->pNext = pDel->pNext;
		free(pDel);
		pDel = NULL;
	}
	free(*pHaed);
	(*pHaed) = NULL;
	return OK;
}


int reverseLink(Link* pHaed)
{
	if (NULL == pHaed)
	{
		return LINKNULL;
	}
	Link* pSecond = pHaed->pNext;
	pHaed->pNext = NULL;
	while (1)
	{
		Link* pDel = pSecond;
		if (NULL == pDel)
		{
			break;
		}
		pSecond = pSecond->pNext;
		pDel->pNext = pHaed->pNext;
		pHaed->pNext = pDel;
	}
	return OK;
}